<template>
  <div class="un-d-tag">
    <el-tag
      :key="tag"
      v-for="tag in dynamicTags"
      closable
      :disable-transitions="false"
      @close="handleClose(tag)"
    >
      {{ tag }}
    </el-tag>
    <el-input
      class="input-new-tag"
      v-if="inputVisible"
      v-model.trim="inputValue"
      ref="saveTagInput"
      size="small"
      @keyup.enter.native="handleInputConfirm"
      @blur="handleInputConfirm"
    >
    </el-input>
    <el-button v-else class="button-new-tag" size="small" @click="showInput"
      >+ New Tag</el-button
    >
  </div>
</template>

<script>
export default {
  name: "UnDTag",
  props: {
    value: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      dynamicTags: this.value || [],
      inputVisible: false,
      inputValue: "",
    };
  },
  watch: {
    value: {
      handler(val) {
        this.dynamicTags = val && val.length ? val : [];
      },
      deep: true,
    },
  },
  methods: {
    handleClose(tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
      this.$emit("input", [...this.dynamicTags]);
    },

    showInput() {
      this.inputVisible = true;
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    handleInputConfirm(e) {
      e.preventDefault();
      let inputValue = this.inputValue;
      if (inputValue) {
        // 去重
        if (this.dynamicTags.includes(inputValue)) {
          this.$message.success("标签已存在");
          return;
        }

        this.dynamicTags.push(inputValue);
      }
      this.inputVisible = false;
      this.inputValue = "";
      this.$emit("input", [...this.dynamicTags]);

      e.stopPropagation();
    },
  },
};
</script>

<style lang="scss">
.un-d-tag {
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
}
</style>
